from table import *
from lib import *
from table import *

def bore(t,target=None) :
  klasses=Deep()
  counts=Deep()
  overall=Deep() 
  unique=Deep()
  ranks=[]
  for row,cells in enumerate(t.data):
    klass = cells[-1]
    if not target: 
      target=klass
    klasses.inc(klass)
    for col,value in enumerate(cells):
      if col != t.klass:
        if value != "?":
          counts[klass][col].inc(value)
          overall[col].inc(value)
          unique[col][value]=1
  us = klasses[target]
  them = len(t.data) - us
  for col,cols in counts[target].items():
    if len(unique[col]) > 1:
      for value,freq in counts[target][col].items():
        b0   = freq
        r0   = overall.at([col,value],0) - b0
        b    = b0 / (us   + 0.00001)
        r    = r0 / (them + 0.00001)
        rank = b*b/(b + r)
        if (b > r):
          ranks.append((rank,t.names[col],value))
  return target,sorted(ranks,key=lambda x: -1*x[0])
  
from pprint import *
@demo
def bored1(f="weather") :
   t= Table(data(f))
   target,results= bore(t)
   for x in results: print x

@demo
def bored2() :
  bored1("autompgd")
